/**
 * 分页查询方法
 * @param url
 * @param pageNo
 * @param pageSize
 */
function submit(url, pageNo, pageSize) {
    if (pageNo === undefined) {
        pageNo = initPageNo;
    }
    if (pageSize === undefined) {
        pageSize = initPageSize;
    }

    layui.use(['table', 'laypage', 'form'], function () {
        let table = layui.table;
        let laypage = layui.laypage;
        let loading = layer.msg('正在查询...', {icon: 16, shade: 0.3, time: 0});
        let templateNo = $('#templateNo').val();
        let templateName = $('#templateName').val();
        let sealType = $('#sealType').val();
        let createTime = $('#createTime').val();
        let updateTime = $('#updateTime').val();

        //第一个实例
        table.render({
            elem: '#searchTable'
            ,
            url: url //数据接口
            ,
            page: false //开启分页
            ,
            toolbar: '#tableToolbar'
            ,
            method: 'POST'
            ,
            height: 'full-280'
            ,
            headers: {"token": getCookie("token")}
            ,
            contentType: "application/json"
            ,
            where: {
                templateNo: templateNo,
                templateName: templateName,
                sealType: sealType,
                createTime: createTime,
                updateTime: updateTime,
                pageNo: pageNo,
                pageSize: pageSize
            }
            ,
            cols: [[ //表头
                {field: 'dataId', type: 'checkbox'}
                , {field: 'templateNo', title: '模板编码', width: '180', align: 'center'}
                , {field: 'templateName', title: '模板名称', width: '180', align: 'center'}
                , {field: 'sealTypeName', title: '签章类型', width: '100', align: 'center'}
                , {field: 'wholeCreateName', title: '创建人', width: '150', align: 'center'}
                , {
                    field: 'createTime', title: '创建时间', width: '150', align: 'center', templet: function (d) {
                        return toDateString(d.createTime);
                    }
                }
                , {field: 'wholeOperatorName', title: '最后一次修改人', width: '150', align: 'center'}
                , {
                    field: 'updateTime', title: '修改时间', width: '150', align: 'center', templet: function (d) {
                        return toDateString(d.updateTime);
                    }
                }
                , {field: 'version', title: '版本', width: '100', align: 'center'}
                , {field: 'remark', title: '备注', width: '180', align: 'center'}
                , {fixed: 'right', width: '250', title: '操作', align: 'center', toolbar: '#barSearch'} //添加工具条,
            ]]
            ,
            parseData: function (res) { //将原始数据解析成 table 组件所规定的数据
                if (res.code == 100) {
                    errorMsg(res.msg);
                } else {
                    return {
                        "code": res.code, //解析接口状态
                        "msg": res.msg, //解析提示文本
                        "count": res.data.pageInfo.totalCount, //解析数据长度
                        "pageNo": res.data.pageInfo.pageNo, //解析数据长度
                        "pageSize": res.data.pageInfo.pageSize, //解析数据长度
                        "data": res.data.pageInfo.list //解析数据列表
                    };
                }
            }
            ,
            done: function (res) {
                layer.close(loading);
                //校验登陆状态
                checkLogin(res);
                //增加自定义样式
                beautyCell();
                //自定义分页
                laypage.render({
                    elem: 'tablePage'
                    , curr: res.pageNo
                    , count: res.count
                    , limit: res.pageSize
                    , layout: ['page', 'limit', 'count', 'skip']
                    , theme: '#1b2b34'
                    , jump: function (obj, first) {
                        if (!first) {
                            submit(url, obj.curr, obj.limit);
                        }
                    }
                });
            }
        });

        //工具条
        table.on('tool(searchTable)', function (obj) {
            let data = obj.data;
            if (obj.event === 'preview') {
                let id = data.id;
                xadmin.open("查看模板", "./look-history.html?id=" + id, 500, 600);
            }
            if (obj.event === 'download') {
                let refId = data.refId;
                if (refId !== null && refId !== "") {
                    exportTemplate(refId);
                } else {
                    errorMsg("模板文件不存在！")
                }
            }
        });

        //头部按钮
        table.on('toolbar(searchTable)', function (obj) {
            let checkStatus = table.checkStatus(obj.config.id);
            if (obj.event === 'export') {
                let data = checkStatus.data;
                if (data.length === 0) {
                    alert("请选择导出模板");
                    return false;
                }
                let ids = [];
                $.each(data, function (i, item) {
                    ids.push(item.refId);
                });
                exportTemplate(ids);
            }
        })

    });
}

/**
 * 查询渠道
 */
function queryChannels(form) {
    let url = serverPre + "/manager/scs/v2/channel/list";
    let content = '<option value="">模板渠道</option>'; //全局变量
    let data = JSON.stringify({'pageNo': '1', 'pageSize': '999'});
    $.ajax({
        url: url,
        data: data,
        type: 'POST',
        contentType: 'application/json',
        headers: {'token': getCookie('token')},
        success: function (res) {
            if (res.code === 0) {
                let result = res.data.pageInfo.list;
                $.each(result, function (i, item) {
                    let channelNo = item.channelNo;
                    let channelName = item.channelName;
                    content += '<option value = "' + channelNo + '">' + channelName + '</option>'
                });
                $("#channelId").html(content);
                form.render('select');
            }
        },
        error: function (err) {
            errorMsg(err);
        }
    });
}

/**
 * 查询公章规则号--单条
 * @param form
 */
function queryOfficalId(id, version, form) {
    let url = serverPre + "/manager/scs/v2/template/history/officialSealId";
    let data = JSON.stringify({'templateNo': id, 'version': version});
    $.ajax({
        url: url,
        type: 'POST',
        data: data,
        contentType: 'application/json',
        headers: {'token': getCookie('token')},
        success: function (res) {
            if (res.code === 0) {
                let result = res.data.list;
                $.each(result, function (i, item) {
                    let code = item.code;
                    let name = item.name;
                    let content = "<input type='checkbox' name='officalSealBox' value='" + code + "' lay-skin='primary' disabled='disabled' checked title='" + name + "'>";
                    $("#officialSealId").append(content);
                });
                form.render();
            }
        },
        error: function (err) {
            errorMsg(err);
        }
    });
}

/**
 * 初始化签章类型--所有
 */
function querySealType(form) {
    let url = serverPre + "/manager/scs/v2/template/sealType/list";
    let content = '<option value="">请选择</option>'; //全局变量
    let data = JSON.stringify({'pageNo': '1', 'pageSize': '999'});
    $.ajax({
        url: url,
        data: data,
        type: 'POST',
        contentType: 'application/json',
        headers: {'token': getCookie('token')},
        success: function (res) {
            if (res.code === 0) {
                let result = res.data.list;
                $.each(result, function (i, item) {
                    let sealType = item.code;
                    let sealTypeName = item.name;
                    content += '<option value = "' + sealType + '">' + sealTypeName + '</option>'
                });
                $("#sealType").html(content);
                form.render('select');
            }
        },
        error: function (err) {
            errorMsg(err);
        }
    });
}

/**
 * 新增模板
 * @param url
 * @param data
 * @returns {boolean}
 */
function saveTemplate(url, data) {
    $.ajax({
        url: url,
        data: data,
        type: 'POST',
        contentType: 'application/json',
        headers: {'token': getCookie('token')},
        success: function (res) {
            if (res.code === 0) {
                layui.use('layer', function () {
                    let layer = layui.layer;
                    layer.msg("保存成功!", {
                        icon: 1,
                        time: 2000,
                        end: function () {
                            var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
                            parent.layer.close(index);
                            parent.location.reload();
                        }
                    });
                });
            }
        },
        error: function (err) {
            errorMsg("保存失败")
        }
    });
    return false;
}

/**
 * 美化按钮样式
 */
function beautyCell() {
    $("[data-field='templateStatusName']").children().each(function (index, item) {
        if (item.textContent === '启用') {
            $(this).css("color", "#228b22");
        }
        if (item.textContent === '停用') {
            $(this).css("color", "#ff0000");
        }
    })
}

/**
 * 查看窗口
 * @param result
 */
function buildHistroyOpenWin(result, form) {
    if (result === undefined || result === null) {
        errorMsg("返回数据为空");
    }
    if (result.templateNo !== "") {
        $('#templateNo').val(result.templateNo);
    }
    if (result.templateName !== "") {
        $('#templateName').val(result.templateName);
    }
    if (result.resourceName !== "") {
        $('#templateResource').val(result.resourceName);
    }
    if (result.sealType === 1) {
        $("#officialSealId").parent().hide();
    } else {
        queryOfficalId(result.templateNo, result.version, form);
    }
    if (result.sealTypeName !== "") {
        $('#sealType').val(result.sealTypeName);
    }
    if (result.officialSealId !== "") {
        $('#officialSealId').val(result.officialSealId);
    }
}

/**
 * 导出模板文件
 */
function exportTemplate(ids) {
    let url = serverPre + "/api/scs/v2/template/history/export/";
    window.location.href = url + ids;
    return false;
}

/**
 * 文件上传
 */
function uploadFile(upload, uploadUrl) {
    upload.render({
        elem: '#uploadFile'
        , url: uploadUrl
        , accept: 'file' //普通文件
        , exts: 'html|ftl'
        , done: function (res) {
            if (res.code === 0) {
                $('#templateExtId').val(res.data.templateExtId);
                alert("上传成功！")
            } else {
                errorMsg("文件上传失败！")
            }
        }
    });
}

/**
 * 提交表单
 * @param formData
 * @param url
 */
function submitForm(commitData, url) {
    layui.use(['form', 'layedit', 'laydate'], function () {
        var form = layui.form;
        //自定义验证规则
        form.verify({
            templateNameVerify: function (value) {
            },
            sealTypeVerify: function (value) {
            },
            officialSealId: function (value) {
            },
        });
        //监听提交
        form.on('submit(submitBtn)', function (data) {
            saveTemplate(url, commitData);
            return false;
        });
    })
}
